import React, { useState, useEffect, useRef, useContext } from 'react'
import useMousePosition from '../hooks/useMousePosition'
import { ThemeContext } from '../App'

const LikeButton: React.FC = () => {
	const [like, setLike] = useState(0)
	const [on, setOn] = useState(true)
	const positions = useMousePosition()
	const likeRef = useRef(0)
	const didMountRef = useRef(false)
	const domRef = useRef<HTMLInputElement | null>(null)
	const theme = useContext(ThemeContext)

	const style = {
		background: theme.background,
		color: theme.color
	}
	function handleAlertClick() {
		setTimeout(() => {
			alert(`You clicked on ${likeRef.current}`)
		}, 3000)
	}

	useEffect(() => {
		console.log('document title effect is running')

		document.title = `点击了 ${like} 次`
	}, [like])

	useEffect(() => {
		if (didMountRef.current) {
			console.log('this is updated')
		} else {
			didMountRef.current = true
		}
	})

	useEffect(() => {
		if (domRef && domRef.current) {
			domRef.current.focus()
		}
	})

	return (
		<>
			<input type="text" ref={domRef} />
			<h2>
				<div>自定义 hook</div>
				X: {positions.x}, Y: {positions.y}
			</h2>
			<button style={style}>
				<span>{like}</span>
				<span
					onClick={() => {
						if (on) {
							setLike(like + 1)
							likeRef.current++
						}
					}}
				>
					👍
				</span>
			</button>
			<button onClick={() => setOn(!on)}>{on ? 'On' : 'Off'}</button>
			<button onClick={handleAlertClick}>Alert!</button>
		</>
	)
}

export default LikeButton
